﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.Data;
using System.Data.SqlClient;

namespace Koonsoft.Tool.ReviewBOSSLog
{
    public class ParseOrderCreatedFailLog : ILogParser
    {
        private SqlConnection sqlconn;
        private SqlCommand sqlcmd;


        #region ILogParser 成员

        public void ImportDataIntoDatabase(string filepath)
        {
            var importDir = ConfigurationManager.AppSettings["OrderCreatedFailLog"];

            if (!System.IO.Directory.Exists(importDir))
            {
                throw new Exception("订单生成日志目录不存在。");
            }


            DirectoryInfo dir = new DirectoryInfo(importDir);

            foreach (FileInfo file in dir.GetFiles("*.txt"))
            {

                Console.WriteLine(file.Name);

                StreamReader sr = new StreamReader(importDir + file.Name, Encoding.Default);
                string strBody = sr.ReadToEnd();
                sr.Close();

                Regex reg = new Regex(@"Begin:==============================================[\s\S]*?End;================================================");

                foreach (Match m in reg.Matches(strBody))
                {
                    string log = m.Value;


                    Regex requestReg = new Regex(@"<UserCreateOrderRequest>[\s\S]*?<SaleChannelID>1</SaleChannelID>[\s\S]*?</UserCreateOrderRequest>");

                    if (requestReg.IsMatch(log))
                    {
                        Regex responseReg = new Regex(@"<UserCreateOrderResponse>[\s\S]*?<Result>1</Result>[\s\S]*?</UserCreateOrderResponse>");

                        if (responseReg.IsMatch(log))
                        {
                            DateTime date = DateTime.Now;

                            Regex timeReg = new Regex(@"((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29))");

                            if (timeReg.IsMatch(log))
                            {
                                date = Convert.ToDateTime(timeReg.Match(log).Value);
                            }

                            string msg = responseReg.Match(log).Value;

                            Regex msgReg = new Regex(@"<Message>[\s\S]*?</Message>");

                            string reason = msgReg.Match(msg).Value.Replace("<Message>", string.Empty);

                            reason = reason.Replace("</Message>", string.Empty);

                            InsertIntoDB(date, reason);
                        }
                    }
                }
            }
        }

        public void InsertIntoDB(DateTime date, string msg)
        {
            const string sql = "insert into SaleToECSSLog values (@date,@reason)";

            sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["LocalServer"].ConnectionString;

            sqlcmd = new SqlCommand();
            sqlcmd.Connection = sqlconn;
            sqlcmd.CommandText = sql;

            sqlcmd.Parameters.Add("@date", SqlDbType.DateTime);
            sqlcmd.Parameters["@date"].Value = date;

            sqlcmd.Parameters.Add("@reason", SqlDbType.NVarChar, 512);
            sqlcmd.Parameters["@reason"].Value = msg;

            try
            {
                sqlcmd.Connection.Open();
                sqlcmd.ExecuteNonQuery();
            }
            finally
            {
                sqlcmd.Connection.Close();
            }

        }

        #endregion
    }
}
